package com.sudao.android.candle;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Environment;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.lang.Comparable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class FileBrowser extends Dialog implements AdapterView.OnItemClickListener,
        DialogInterface.OnCancelListener {

	private class IconifiedText implements Comparable<IconifiedText> {
		
		private String text = "";
		private Drawable icon;
		private boolean isFolder;
		private boolean isUpLevelFolder = false;

		IconifiedText(String text, Drawable icon, boolean isFolder, boolean uplevel) {
			this.icon = icon;
			this.text = text;
			this.isFolder = isFolder;
			this.isUpLevelFolder = uplevel;
		}
	
		boolean isFolder() {
			return this.isFolder;
		}
	
		boolean isUpLevelFolder() {
			return this.isUpLevelFolder;
		}
	
		String getText() {
			return text;
		}
	
		Drawable getIcon() {
			return icon;
		}

		@Override
		public int compareTo(IconifiedText other) {
			if(text != null)
				return text.compareTo(other.getText()); 
			else 
				return -1;
		}
	}

	public class IconifiedTextListAdapter extends BaseAdapter {

		private Context context;
		private List<IconifiedText> items = new ArrayList<IconifiedText>();

		IconifiedTextListAdapter(Context context) {
			this.context = context;
		}

		void addItem(IconifiedText it) { items.add(it); }
		void setListItems(List<IconifiedText> lit) { items = lit; }
        @Override
		public int getCount() { return items.size(); }
        @Override
		public IconifiedText getItem(int position) { return items.get(position); }
		boolean areAllItemsSelectable() { return false; }
		boolean isSelectable(int position) { 
			return true;
		}

        @Override
		public long getItemId(int position) {
			return position;
		}

        @Override
		public View getView(int position, View convertView, ViewGroup parent) {
			IconifiedTextView btv;
			if (convertView == null) {
				btv = new IconifiedTextView(context, items.get(position));
			} else {
				btv = (IconifiedTextView) convertView;
				btv.setText(items.get(position).getText());
				btv.setIcon(items.get(position).getIcon());

			}

			if (parent == mPlayListView) {
				if (position == activity.mMusicPlayer.getCurrentSong())
					btv.setTextColor(Color.YELLOW);
				else
					btv.setTextColor(Color.LTGRAY);
				
			}

			return btv;
		}
	}
	
	public class IconifiedTextView extends LinearLayout {
	
		private TextView text;
		private ImageView icon;
	
		IconifiedTextView(Context context, IconifiedText aIconifiedText) {
			super(context);

			this.setOrientation(HORIZONTAL);

			icon = new ImageView(context);
			icon.setImageDrawable(aIconifiedText.getIcon());
			icon.setPadding(0, 2, 5, 0);
			addView(icon,  new LinearLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		
			text = new TextView(context);
			text.setText(aIconifiedText.getText());
			addView(text, new LinearLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		}

		void setText(String words) {
			text.setText(words);
		}
	
		void setTextColor(int color) {
			text.setTextColor(color);
		}

		void setIcon(Drawable bullet) {
			icon.setImageDrawable(bullet);
		}
	}

	private String root = "/sdcard";
	private File currentDirectory;
	private List<IconifiedText> listEntry;
	private List<IconifiedText> playListEntry;
    private String selectedFilePath;
    private CandleActivity activity;

	IconifiedTextListAdapter mFileListAdapter;
	ListView mFileListView;

	IconifiedTextListAdapter mPlayListAdapter;
	ListView mPlayListView;
	private PlayList mPlayList;
	private ArrayList<String> mSongPathList = new ArrayList<String>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.file_browser);
        setOnCancelListener(this);

		if (isSdcardMounted())
			root = "/sdcard";
		currentDirectory = new File(root);
		listEntry = new ArrayList<IconifiedText>();
        mFileListView = (ListView) findViewById(R.id.file_browser_list);
		mFileListAdapter = new IconifiedTextListAdapter(getContext());
		mFileListAdapter.setListItems(listEntry);
        mFileListView.setAdapter(mFileListAdapter);
        mFileListView.setOnItemClickListener(this);

		playListEntry = new ArrayList<IconifiedText>();
		if (mPlayList != null) {
			ArrayList<String> list = mPlayList.getSongs();
			if (list != null && !list.isEmpty()) {
				for (int i = 0; i < list.size(); i++) {
					File f = new File(list.get(i));
					Drawable icon = getContext().getResources().getDrawable(R.drawable.ic_file); 
					playListEntry.add(new IconifiedText(f.getName(), icon, false, false));
					mSongPathList.add(list.get(i));
				}
			}
		}

		mPlayListAdapter = new IconifiedTextListAdapter(getContext());
        mPlayListView = (ListView) findViewById(R.id.play_list);
		mPlayListAdapter.setListItems(playListEntry);
        mPlayListView.setAdapter(mPlayListAdapter);
        mPlayListView.setOnItemClickListener(this);
		
		browseTo(currentDirectory);
	}

	void refresh() {
		if (mPlayListAdapter != null)
			mPlayListAdapter.notifyDataSetChanged();
	}

	FileBrowser(Context context, CandleActivity activity) {
        super(context, android.R.style.Theme);
        this.activity = activity;
	}

	public void setPlayList(PlayList l) {
		mPlayList = l;
	}

	public static boolean isSdcardMounted() {
        String state = Environment.getExternalStorageState();
        return (state.equals(Environment.MEDIA_MOUNTED)
                || state.equals(Environment.MEDIA_MOUNTED_READ_ONLY));
    }

	private void upOneLevel(){
		if(!currentDirectory.getAbsolutePath().equals(root))
			browseTo(currentDirectory.getParentFile());
	}
	
	private void browseTo(final File aDirectory) {
        String title = aDirectory.getAbsolutePath();
		if (aDirectory.isDirectory()){
            setTitle(title);
			currentDirectory = aDirectory;
			fill(aDirectory.listFiles());
		} else {
			finish();
            Context context = getContext();
            String errorMsg = context.getString(R.string.error_not_dir,
                    title);
            Toast.makeText(context, errorMsg, Toast.LENGTH_LONG).show();
		}
	}
	
	private static boolean isAudioFile(String name) {
		if (name.toLowerCase().endsWith("mp3") || name.toLowerCase().endsWith("wma"))
			return true;
		return false;
	}

	private void fill(File[] files) {
		
		List<IconifiedText> directories = new ArrayList<IconifiedText>();
		List<IconifiedText> normalfiles = new ArrayList<IconifiedText>();
        Context context = getContext();
		
		Drawable currentIcon = null;
		for (File currentFile : files){
			String fileName = currentFile.getName();
			if (currentFile.isDirectory()) {
				currentIcon = context.getResources().getDrawable(
                        R.drawable.ic_folder);
				directories.add(
						new IconifiedText(fileName, currentIcon, true, false));
			} else {
				if (!isAudioFile(fileName))
					continue;
				currentIcon = context.getResources().getDrawable(R.drawable.ic_file); 
				normalfiles.add(
						new IconifiedText(fileName, currentIcon, false, false));
			}

		}
		Collections.sort(directories);
		Collections.sort(normalfiles);
		
		// the ".." == 'Up one level'
		if(currentDirectory.getParent() != null && !currentDirectory.getAbsolutePath().equalsIgnoreCase(root)) {
			if (directories.isEmpty())
				directories.add(new IconifiedText(
					context.getString(R.string.up_one_level), 
					context.getResources().getDrawable(
                        R.drawable.ic_up_one_level), 
					true, true));
			else
				directories.add(0, new IconifiedText(
					context.getString(R.string.up_one_level), 
					context.getResources().getDrawable(
                        R.drawable.ic_up_one_level), 
					true, true));
		}

		listEntry.clear();
		listEntry.addAll(directories);
		listEntry.addAll(normalfiles);
		//mFileListAdapter.setListItems(listEntry);
		mFileListAdapter.notifyDataSetChanged();
	}

	private void addToPlayList(IconifiedText it, String path) {
		Drawable currentIcon = null;
		currentIcon = getContext().getResources().getDrawable(R.drawable.ic_file); 
		playListEntry.add(it);
		mSongPathList.add(path);
		mPlayList.updateSongs(mSongPathList);
		refresh();
        //list.setOnItemClickListener(this);
	}

	public void removeFromPlayList(int position) {
		playListEntry.remove(position);
		mSongPathList.remove(position);
		mPlayList.updateSongs(mSongPathList);
		activity.mMusicPlayer.setSongList();
		activity.mMusicPlayer.setCurrentSongForRemove(position);
		refresh();
	}

	@Override
	public void onItemClick(AdapterView parent, View v, int position, long id) {
		if (parent == mFileListView) {
			IconifiedText it = listEntry.get(position);
			String absoluteFilePath = currentDirectory.getAbsolutePath() + "/" + it.getText();
			if (it.isFolder()) {
				if (it.isUpLevelFolder()) {
					upOneLevel();
				} else {
					browseTo(new File(absoluteFilePath));
				}
			} else {
				String fileName = new File(absoluteFilePath).getName();
                selectedFilePath = absoluteFilePath;
				addToPlayList(it, selectedFilePath);
			}
		} else if (parent == mPlayListView) {
			activity.mOperatedSongIndex = position;
			activity.showDialog(activity.DIALOG_PLAY_REMOVE);
		}
	}

	public void playFromPlayList(int position) {
		if (mSongPathList != null && !mSongPathList.isEmpty()) {
			activity.mMusicPlayer.setCurrentSong(position);
			activity.mMusicPlayer.playMedia();
			refresh();
		}
	}

    @Override
    public void onCancel(DialogInterface dialog) {
        finish();
    }

    private void finish() {
		mPlayList.updateSongs(mSongPathList);
		if (mSongPathList != null && !mSongPathList.isEmpty()) {
			//activity.mMusicPlayer.setCurrentSong(activity.mMusicPlayer.getCurrentSong());
			activity.mMusicPlayer.playMedia();
		}
        activity.removeDialog(CandleActivity.DIALOG_FILE_BROWSER);
    }

    String getSelectedFilePath() {
        return selectedFilePath;
    }
}

